<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Chat Room</title>
  <script src="./socket.io.js"></script>
  <script>
    var socket = io("ws://127.0.0.1:8787", {
      transports: ['websocket']
    });
    window.onload = function() {
      const form = document.getElementById('form');
      const input = document.getElementById('input');
      const messages = document.getElementById('messages');

      form.addEventListener('submit', function(e) {
        e.preventDefault();
        if (input.value) {
          socket.emit('chat message', input.value);
          input.value = '';
        }
      });
      socket.on("connect", () => {
        console.log('socket.id:', socket.id);
        socket.emit('chat message', 'Welcome to the chat room!');
      });
      socket.on('chat message', function(msg) {
        console.log(msg);
        const item = document.createElement('li');
        item.textContent = msg;
        messages.appendChild(item);
        window.scrollTo(0, document.body.scrollHeight);
      });
    };
  </script>
</head>
<body>
<ul id="messages"></ul>
<form id="form" action="">
  <input id="input" autocomplete="off" /><button>Send</button>
</form>
</body>
</html>
